package cn.vcjf.weapp.api.user.service.impl;

import cn.vcjf.weapp.api.setting.entity.OrderOption;
import cn.vcjf.weapp.api.setting.mapper.OrderOptionMapper;
import cn.vcjf.weapp.api.user.entity.User;
import cn.vcjf.weapp.api.user.entity.UserProfit;
import cn.vcjf.weapp.api.user.entity.UserWallet;
import cn.vcjf.weapp.api.user.mapper.UserMapper;
import cn.vcjf.weapp.api.user.mapper.UserProfitMapper;
import cn.vcjf.weapp.api.user.mapper.UserWalletMapper;
import cn.vcjf.weapp.api.user.service.UserProfitService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhengzihang
 * @since 2018-09-25
 */
@Service("userProfitService")
public class UserProfitServiceImpl extends ServiceImpl<UserProfitMapper, UserProfit> implements UserProfitService {

	private Logger logger = LogManager.getLogger(this.getClass());
	@Resource
	private UserWalletMapper userWalletMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private OrderOptionMapper orderOptionMapper;

	@Override
	public List<UserProfit> selectIndirectSubordinates(Page<UserProfit> page, UserProfit userProfit) {
		return baseMapper.selectIndirectSubordinates(page,userProfit);
	}

	@Override
	public List<UserProfit> selectUserProfitPage(Page<UserProfit> page, UserProfit userProfit) {
		return baseMapper.selectPage(page,userProfit);
	}

	/**
	 * 添加分润
	 * @param userProfit
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int addUserProfit(UserProfit userProfit) {
		userProfit.preInsert();
		baseMapper.insert(userProfit);

		UserWallet userWallet = new UserWallet();
		userWallet.setUserId(userProfit.getUserId());
		userWallet.setSysUserId(userProfit.getSysUserId());
		userWallet.setProfit(userProfit.getProfitMoney());

		userWalletMapper.addUserWallet(userWallet);
		return 0;
	}
	/**
	 * 计算添加分润   <br>
	 * require{         <br>
	 *   orderNo        <br>
	 *   orderMoney;    <br>
	 *   userId    //交易人id  <br>
	 *  }
	 * @param userProfit
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public int calculateUserProfit(UserProfit userProfit) {
		User user = new User();
		user.setId(userProfit.getUserId());
		user.setSysUserId(userProfit.getSysUserId());
		
		//直接下级
		logger.info("直接下级分润开始");
		List<User> userLowerLevelList = userMapper.getUserLowerLevel(user);
		if (userLowerLevelList != null){
			OrderOption orderOption = new OrderOption();
			orderOption.setKey("profit_scale");
			OrderOption option = orderOptionMapper.selectOne(orderOption);
			userProfit.setProfitType(1);
			addProfit(userLowerLevelList, userProfit, option);
		}
		//间接下级
		logger.info("间接下级分润开始");
		List<User> userIndirectLowerLevelList = userMapper.getIndirectLowerLevel(user);
		if (userLowerLevelList != null){
			OrderOption orderOption = new OrderOption();
			orderOption.setKey("profit_indirect_scale");

			OrderOption option = orderOptionMapper.selectOne(orderOption);
			userProfit.setProfitType(2);
			addProfit(userIndirectLowerLevelList, userProfit, option);
		}
		userProfit.preInsert();
		baseMapper.insert(userProfit);

		return 0;
	}

	private void addProfit(List<User> userList, UserProfit userProfit, OrderOption option ){
		if(option.getValue()==null||option.getIntValue()>1||option.getIntValue()<0){
			logger.info("没有配置直接下级分润比例或比例配置不正确:{},比例设置为0",option.getValue());
			option.setIntValue(0);
		}
		logger.info("下级分润比例为:{}",option.getValue());
		BigDecimal profitScale = new BigDecimal(option.getValue());

		userProfit.setProfitPercent(profitScale);

		BigDecimal orderMoney = userProfit.getOrderMoney();
		BigDecimal profit = orderMoney.multiply(profitScale.divide(new BigDecimal(100)));
		userProfit.setProfitMoney(profit);
		logger.info("交易金额为:{},下级分润为:{}",orderMoney,profit);
		List<Integer> userIds = new ArrayList<>();
		for(User user1 : userList){
			userIds.add(user1.getId());
			//添加分润记录
			userProfit.setUserId(user1.getId());
			userProfit.preInsert();
			baseMapper.insert(userProfit);
		}
		userWalletMapper.updateBatchUsersWatter(userIds, userProfit);


	}
}
